package com.edu.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.edu.bean.Carimg;
import com.edu.service.CarimgService;
import com.edu.service.impl.CarimgServiceImpl;
@WebServlet("/updatecarimgform.do")
@MultipartConfig(
	    maxFileSize = 1024 * 1024 * 10,    // 10MB
	    maxRequestSize = 1024 * 1024 * 50  // 50MB
	)
public class UpdateCarimgServlet extends HttpServlet{
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("application/json");
        PrintWriter out = resp.getWriter();
        Map<String, Object> responseData = new HashMap<>();
		try {
		    // 获取表单数据
		    int id = Integer.parseInt(req.getParameter("id"));
		    int carId = Integer.parseInt(req.getParameter("carid"));

		    // 获取原有数据
		    CarimgService carimgService = new CarimgServiceImpl();
		    Carimg oldCarImg = carimgService.selectCommentById(id);
		    Carimg newCarImg = new Carimg();
		    newCarImg.setCarimgid(id);
		    newCarImg.setCarid(carId);

		    // 处理上传文件
		    Collection<Part> parts = req.getParts();
		    for (Part part : parts) {
		        String fieldName = part.getName();
		        String fileName = part.getSubmittedFileName();
		        
		        System.out.println("Processing field: " + fieldName);
		        
		        // 跳过非文件字段
		        if (fileName == null || fileName.isEmpty()) {
		            System.out.println("Skipping non-file field: " + fieldName);
		            continue;
		        }

		        // 校验文件
		        if (part.getSize() > 1024 * 1024) {
		            responseData.put("success", "false");
		            responseData.put("message", fieldName + "图片大小不能超过1MB");
		            return;
		        }
		        if (!part.getContentType().startsWith("image/")) {
		            responseData.put("success", "false");
		            responseData.put("message", fieldName + "只能上传图片文件");
		            return;
		        }

		        // 生成新文件名
		        String newFileName = carId + "_" + System.currentTimeMillis() + "_" + fileName;
		        String savePath = "C:/PhaetonCommunityImg/favoriteCar/" + newFileName;
		        String visitPath = "/PhaetonCommunity/favoriteCar/" + newFileName;

		        // 保存文件
		        part.write(savePath);
		        System.out.println("File saved: " + savePath);

		        // 根据字段名设置路径
		        switch (fieldName) {
		            case "carImgKV":
		                newCarImg.setCarimgkv(visitPath);
		                deleteOldFile(oldCarImg.getCarimgkv());
		                break;
		            case "carImgIVI":
	                    newCarImg.setCarimgivi(visitPath);
	                    deleteOldFile(oldCarImg.getCarimgivi());
	                    break;
	                case "frontFender":
	                    newCarImg.setFrontFender(visitPath);
	                    deleteOldFile(oldCarImg.getFrontFender());
	                    break;
	                case "carImgAc":
	                    newCarImg.setCarImgAc(visitPath);
	                    deleteOldFile(oldCarImg.getCarImgAc());
	                    break;
	                case "carImgMph":
	                    newCarImg.setCarImgMph(visitPath);
	                    deleteOldFile(oldCarImg.getCarImgMph());
	                    break;
	                case "carImgAudio":
	                    newCarImg.setCarImgAudio(visitPath);
	                    deleteOldFile(oldCarImg.getCarImgAudio());
	                    break;
	                case "carImgSeat":
	                    newCarImg.setCarImgSeat(visitPath);
	                    deleteOldFile(oldCarImg.getCarImgSeat());
	                    break;
	                case "carImgSunroof":
	                    newCarImg.setCarImgSunroof(visitPath);
	                    deleteOldFile(oldCarImg.getCarImgSunroof());
	                    break;
		            default:
		                System.out.println("Unknown field name: " + fieldName);
		        }
		    }

		    // 更新数据库
		    int result = carimgService.updateCarimg(newCarImg);
		    if (result > 0) {
		        responseData.put("success", "true");
		        responseData.put("message", "图片更新成功");
		    } else {
		        responseData.put("success", "false");
		        responseData.put("message", "数据库更新失败");
		    }
		} catch (Exception e) {
		    responseData.put("success", "false");
		    responseData.put("message", "服务器错误: " + e.getMessage());
		    e.printStackTrace();
		} finally {
		    out.close();
		}
	}

	private void deleteOldFile(String carimgkv) {
		// TODO Auto-generated method stub
		
	}	
}
